package com.example.srm.auth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.srm.auth.service.TPermissionService;
import com.example.srm.domain.TPermission;
import com.example.srm.domain.tree.Tree;
import com.example.srm.auth.mapper.TPermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 *
 */
@Service
public class TPermissionServiceImpl extends ServiceImpl<TPermissionMapper, TPermission> implements TPermissionService {
    
    @Autowired
    private TPermissionMapper permissionMapper;

    /**
     * 将树结点对象集合转为树结构集合
     * @param list
     * @return
     */
    private List<Tree> toTree(List<Tree> list) {
        HashMap<String, Tree> map = new HashMap<>();
        list.forEach(e->map.put(e.getId(),e));

        List<Tree> list1 = new ArrayList<>();

        for (Tree tree : list) {
            Tree parent = map.get(tree.getPid());
            if (parent==null){
                //解决前端的bug，需要在根节点设置 false
                tree.setChecked(false);
                tree.setState("open");
                list1.add(tree);
            }else {
                if (parent.getChildren()==null){
                    parent.setChildren(new LinkedList<>());
                }
                tree.setState("chose");
                parent.getChildren().add(tree);
            }
        }
        return list1;
    }

    @Override
    public List<Tree> findPermissionTree() {
        List<Tree> list = permissionMapper.listTree();
        List<Tree> jsonTreeData = toTree(list);
        return jsonTreeData;
    }
}




